<!-- 工单工艺 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @row-click="rowClick"
      @on-load="onLoad"
      @select="handSelect"
      @select-all="selectionAll"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" size="small" icon="el-icon-edit" v-if="scope.row.status == 3" @click="$refs.crud.rowEdit(scope.row, scope.index)">编辑</el-button>
        <el-button type="text" icon="el-icon-view" size="small" v-if="permission.workorder_view" @click.stop="handleView(scope.row)">详情</el-button>
      </template>
      <template slot="menuLeft">
        <!-- 设计工艺路线 -->
        <el-button type="warning" size="small" icon="el-icon-edit" v-if="permission.workorderRoute_gdesign" @click="handleMenu({ type: 'gdesign' })">编辑工艺路线</el-button>
        <!-- 查看工艺路线 -->
        <el-button type="primary" size="small" icon="el-icon-search" v-if="permission.workorderRoute_gread" @click="handleMenu({ type: 'gread' })">查看工艺路线</el-button>
        <el-button type="success" size="small" icon="el-icon-setting" v-if="permission.workorderRoute_materialConfig" @click="orderPartConfig">产品用料配置</el-button>
        <el-button type="success" size="small" icon="el-icon-refresh" @click="handleMenu({ type: 'processSync' })">同步产品工艺</el-button>
      </template>
    </avue-crud>
    <el-dialog ref="dialog" custom-class="workorderRouteDialog" width="80%" title="查看" append-to-body :visible.sync="showDetailDialog" top="5vh">
      <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName">
          <span>基础信息</span>
        </div>
      </div>
      <avue-form ref="form" v-model="form" :option="basicInfoOption"></avue-form>
      <!-- <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName">
          <span>操作日志</span>
        </div>
      </div>
      <avue-crud :option="logOption" :data="logData" ref="crud"></avue-crud> -->
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDetailDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-dragDirectives
      class="keyMaterialsDialog"
      ref="dialog"
      title="产品用料配置"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="5vh"
      width="90%"
      @close="closeDialog"
    >
      <avue-form ref="basicInfoForm" v-if="showDialog" v-model="basicInfoForm" :option="dialogOption"></avue-form>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>生产用料配置</h3>
      <el-row style="margin-bottom: 10px">
        <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="addMaterial('partModal')">添加物料</el-button>
        <el-button v-if="dialogTitle != '详情'" type="danger" size="small" icon="el-icon-delete" @click="productInfoDelete">删 除</el-button>
        <!-- <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport('detail')">导入</el-button> -->
      </el-row>
      <vxe-grid ref="productInfoCrud" v-bind="gridOptions" v-loading="loading" :data="productInfoList">
        <template #sectionId_default="{ row, rowIndex }">
          <el-select v-model="row.sectionId" placeholder="请选择" size="small" @change="sectionChange(rowIndex)">
            <el-option v-for="item in sectionList" :key="item.sectionId" :label="item.sectionName" :value="item.sectionId"> </el-option>
          </el-select>
        </template>
        <template #materialProcessName_default="{ row, rowIndex }">
          <el-select
            v-model="row.materialProcessName"
            placeholder="请选择 生产工序"
            size="small"
            :clearable="true"
            :disabled="dialogTitle == '详情'"
            @focus="materialProcessChange(row.sectionId)"
            @change="handleChangeMaterialProcess(row.materialProcessName, rowIndex)"
          >
            <el-option v-for="item in workProcessList" :key="item.id" :label="item.materialProcessName" :value="item.materialProcessName"></el-option>
          </el-select>
        </template>
        <template #quantity_default="{ row }">
          <el-input-number v-model="row.quantity" size="small" name="quantity" :controls="false" style="width: 100%" :disabled="dialogTitle == '详情'"></el-input-number>
        </template>
        <template #isKeyMaterial_default="{ row }">
          <el-select v-model="row.isKeyMaterial" placeholder="请选择" size="small" :disabled="dialogTitle == '详情'">
            <el-option label="是" :value="true"> </el-option>
            <el-option label="否" :value="false"> </el-option>
          </el-select>
        </template>
        <template #isBackflush_default="{ row }">
          <el-select v-model="row.isBackflush" placeholder="请选择" size="small" :disabled="dialogTitle == '详情'">
            <el-option label="是" :value="true"> </el-option>
            <el-option label="否" :value="false"> </el-option>
          </el-select>
        </template>
        <template #backflushWarehouseId_default="{ row }">
          <el-select v-model="row.backflushWarehouseId" placeholder="请选择" size="small" :clearable="true" :disabled="dialogTitle == '详情'">
            <el-option v-for="item in warehouseList" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </template>
        <template #fixed_default="{ row, rowIndex }" v-if="dialogTitle != '详情'">
          <el-button size="small" type="text" icon="el-icon-delete" @click="productInfoRowDel(row, rowIndex)">删除</el-button>
          <el-button type="text" size="small" @click="handleAddMaterial(row, rowIndex)">添加替代料</el-button>
        </template>
      </vxe-grid>
      <!-- <el-table v-loading="loading" ref="productInfoCrud" height="200px" :data="productInfoList" border style="width: 100%" @selection-change="basicInfoSelectionChange">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" width="50" align="center"></el-table-column>
        <el-table-column v-for="item in productInfoOption.column" :label="item.label" :prop="item.prop" :key="item.prop">
          <template slot-scope="scope">
            <span v-if="item.prop === 'quantity'">
              <el-input-number v-model="scope.row.quantity" name="quantity" :controls="false" style="width: 100%" :disabled="dialogTitle == '详情'"></el-input-number>
            </span>
            <span v-else-if="item.prop === 'sectionId'">
              <el-select v-model="scope.row.sectionId" placeholder="请选择" size="small" @change="sectionChange(scope.$index)">
                <el-option v-for="item in sectionList" :key="item.sectionId" :label="item.sectionName" :value="item.sectionId"> </el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'materialProcessName'">
              <el-select
                v-model="scope.row.materialProcessName"
                placeholder="请选择 生产工序"
                :clearable="true"
                :disabled="dialogTitle == '详情'"
                @focus="materialProcessChange(scope.row.sectionId)"
                @change="handleChangeMaterialProcess(scope.row.materialProcessName, scope.$index)"
              >
                <el-option v-for="item in workProcessList" :key="item.id" :label="item.materialProcessName" :value="item.materialProcessName"></el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'isKeyMaterial'">
              <el-select v-model="scope.row.isKeyMaterial" placeholder="请选择" :disabled="dialogTitle == '详情'">
                <el-option label="是" :value="true"> </el-option>
                <el-option label="否" :value="false"> </el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'isBackflush'">
              <el-select v-model="scope.row.isBackflush" placeholder="请选择" :disabled="dialogTitle == '详情'">
                <el-option label="是" :value="true"> </el-option>
                <el-option label="否" :value="false"> </el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'backflushWarehouseId'">
              <el-select v-model="scope.row.backflushWarehouseId" placeholder="请选择" :clearable="true" :disabled="dialogTitle == '详情'">
                <el-option v-for="item in warehouseList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" v-if="dialogTitle != '详情'">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="productInfoRowDel(scope.row, scope.$index)">删除</el-button>
            <el-button type="text" size="small" @click="handleAddMaterial(scope.row, scope.$index)">添加替代料</el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submit"><i class="el-icon-circle-check"></i><span>修 改</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog
      class="replaceDialog"
      ref="dialog"
      title="添加替代料"
      append-to-body
      :visible.sync="alternativeMaterialsDialog"
      :close-on-click-modal="false"
      top="5vh"
      width="70%"
      @close="replaceClose"
    >
      <avue-form v-if="alternativeMaterialsDialog" ref="partForm" v-model="partForm" :option="partOption"></avue-form>
      <el-row style="margin-bottom: 10px">
        <el-button v-if="dialogTitle != '详情'" type="primary" icon="el-icon-plus" size="small" @click="addReplace">新增行</el-button>
      </el-row>
      <el-table height="500px" :data="alternativeMaterialsList" border style="width: 100%">
        <el-table-column type="index" width="50" align="center"></el-table-column>
        <el-table-column v-for="item in alternativeMaterialsOption" :label="item.label" :prop="item.prop" :key="item.prop">
          <template slot-scope="scope">
            <span v-if="item.prop === 'partNo'">
              <el-input v-model="scope.row.partNo" :disabled="dialogTitle == '详情'">
                <el-button slot="append" icon="el-icon-search" @click="openSelectReplaceModal(scope.$index)"></el-button>
              </el-input>
            </span>
            <span v-else-if="item.prop === 'quantity'">
              <el-input-number v-model="scope.row.quantity" name="quantity" :controls="false" style="width: 100%" :disabled="dialogTitle == '详情'"></el-input-number>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" v-if="dialogTitle != '详情'">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="replacePartRowDel(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="alternativeMaterialsDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button type="primary" size="small" @click="submitReplacePart"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
      </span>
    </el-dialog>
    <!-- 物料基础数据 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.importUrl"
      :formData="importConfig.formData"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
  </basic-container>
</template>

<script>
import {
  byPartmasterPrePart,
  exportSN,
  getList,
  getDetail,
  add,
  update,
  remove,
  workDispatch,
  workFinished,
  workWithdraw,
  findProductionlineList,
  getProductMaterialConfig,
  getWorkorderRoute,
  writeWorkOrder,
  writeBillMaterial,
  productProcessSync,
  checkProcessRoute
} from '@/api/product/workorderRoute';
import { getConfiguration } from '@/api/product/product-material-config';
import { paramDetail, processAudit, getProcessLog, getSectionByPartId } from '@/api/product/productrouteManage';
import { getList as getPartMasterList } from '@/api/admin/partmaster';
import { getValidateSationList } from '@/api/product/product-material-config';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { mapGetters, mapState } from 'vuex';
import { compareTime, handleJumpCache } from '@/util/util';
import { getList as getBomList } from '@/api/admin/bom';
import { addOrUpdate, getWarehouseList } from '@/api/product/product-material-config';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import importDialogComp from '@/components/dialog/import/index.vue';
export default {
  name: 'workorderRoute',
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    userTableConfig,
    importDialogComp
  },
  mixins: [userConfig()],
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      pageCode: 'WORKORDER_ROUTE',
      gridOptions: {
        border: true,
        showOverflow: true,
        height: 450,
        scrollY: {
          enabled: true,
          gt: 0
        },
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', title: '序号', width: 50 },
          { field: 'partNo', title: '物料编码' },
          { field: 'partName', title: '物料名称' },
          { field: 'partSpec', title: '物料规格' },
          { field: 'sectionId', title: '用料工段', slots: { default: 'sectionId_default' } },
          { field: 'materialProcessName', title: '用料工序', slots: { default: 'materialProcessName_default' } },
          { field: 'quantity', title: '单位用量', slots: { default: 'quantity_default' } },
          { field: 'isKeyMaterial', title: '是否关键料', slots: { default: 'isKeyMaterial_default' }, width: 100 },
          { field: 'isBackflush', title: '是否倒冲', slots: { default: 'isBackflush_default' }, width: 100 },
          { field: 'backflushWarehouseId', title: '倒冲仓库', slots: { default: 'backflushWarehouseId_default' } },
          { field: 'fixed', title: '操作', width: 150, slots: { default: 'fixed_default' } }
        ]
      },
      // 工单用量配置参数
      workOrderMaterialsParams: {
        workOrderId: '',
        workOrderNo: '',
        partMasterId: ''
      },
      partMasterId: '',
      firstToEdit: true,
      visibile: false,
      rowIndex: '',
      form: {},
      query: {},
      search: {},
      defaults: {},
      loading: true,
      data: [],
      commonDialog: {
        dispatch: true
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      // 1：待排程；2：待生产；3：生产中；4：完工；5：锁定；6：强制完工；';
      // workOrderStatus: ['待排程', '待生产', '生产中',  '完工', '锁定', '强制完工'],
      selectionList: [],
      option: {
        height: 'calc(100vh - 406px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        searchLabelWidth: 100,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: true,
        menuWidth: 150,
        labelWidth: 160,
        dialogDrag: true,
        highlightCurrentRow: true,
        columnBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true,
            width: 150,
            search: true
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            disabled: true,
            search: true
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            disabled: true,
            search: true
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            disabled: true,
            search: true
          },
          {
            label: '工单计划数',
            prop: 'planQuantity',
            disabled: true,
            width: 100
          },
          {
            label: 'BOM版本',
            disabled: true,
            prop: 'bomVersion'
          },

          {
            label: '工艺路线状态',
            width: 120,
            prop: 'status',
            type: 'select',
            editDisplay: false,
            search: true,
            dicData: [
              {
                label: '未设计',
                value: 1
              },
              {
                label: '待审核',
                value: 2
              },
              {
                label: '已发布',
                value: 3
              }
            ],
            html: true,
            formatter: (val) => this.$statusText.GYLX(val.status)
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            width: 60,
            span: 24,
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          },
          {
            label: '更新人',
            prop: 'updateUserName',
            search: true,
            editDisplay: false
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            search: true,
            type: 'datetime',
            width: 130,
            editDisplay: false,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          }
        ]
      },
      productionlineList: [], //产线列表
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            span: 8,
            disabled: true
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            span: 8,
            disabled: true
          }
        ]
      },
      basicInfoForm: {},
      data: [],
      productInfoKey: 'init',
      productInfoOption: {
        height: 450,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        cellBtn: true,
        menu: true,
        menuWidth: 280,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '用料工段',
            prop: 'sectionId',
            cell: true,
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请输入用料工段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '用料工序',
            prop: 'materialProcessName',
            cell: true,
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择用料工序',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单位用量',
            prop: 'quantity',
            cell: true,
            type: 'number',
            controls: false,
            precision: 10,
            rules: [
              {
                required: true,
                message: '请输入单位用量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否关键料',
            prop: 'isKeyMaterial'
          },
          {
            label: '是否倒冲',
            prop: 'isBackflush'
          },
          {
            label: '倒冲仓库',
            prop: 'backflushWarehouseId'
          }
        ]
      },
      workProcessList: [],
      productInfoList: [],
      basicInfoSelectionList: [],
      processId: '', //工艺ID,
      sectionList: [],
      materialControlsDeleteIds: [],
      selectTimeControlIndex: 0,
      isAudit: false,
      showDetailDialog: false,
      basicInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        detail: true,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            span: 8,
            width: 150
          },
          {
            label: '产品编码',
            span: 8,
            prop: 'productPartNo'
          },
          {
            label: '产品名称',
            span: 8,
            prop: 'productPartName'
          },
          {
            label: 'BOM版本',
            span: 8,
            prop: 'bomVersion'
          },
          {
            label: '工单计划数',
            prop: 'planQuantity',
            span: 8,
            width: 100
          },
          {
            label: '工艺路线状态',
            width: 120,
            span: 8,
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '未设计',
                value: 1
              },
              {
                label: '待审核',
                value: 2
              },
              {
                label: '已发布',
                value: 3
              }
            ],
            html: true,
            formatter: (val) => this.$statusText.GYLX(val.status)
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            width: 60,
            span: 24,
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          }
        ]
      },
      logOption: {
        height: 300,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        menu: false,
        menuWidth: 180,
        refreshBtn: false,
        column: [
          {
            label: '编辑内容',
            prop: 'remark'
          },
          {
            label: '编辑原因',
            prop: 'reason'
          },
          {
            label: '编辑人',
            prop: 'createBy'
          },
          {
            label: '编辑时间',
            prop: 'createTime'
          }
        ]
      },
      logData: [],
      showMaterialDialog: false,
      showBomDialog: false,
      addPartType: '',
      selectSectionDialogForm: {},
      selectSectionOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '用料工段',
            type: 'select',
            span: 8,
            prop: 'sectionId',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择用料工段',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      alternativeMaterialsList: [],
      alternativeMaterialsDialog: false,
      alternativeMaterialsOption: [
        {
          label: '替代物料编码',
          prop: 'partNo'
        },
        {
          label: '替代物料名称',
          prop: 'partName'
        },
        {
          label: '替代物料规格',
          prop: 'partSpec'
        },
        {
          label: '单位用量',
          prop: 'quantity'
        }
      ],
      replaceRowIndex: '',
      partForm: {},
      partOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: '物料编码',
            prop: 'productPartNo',
            span: 8,
            labelWidth: '85',
            disabled: true
          },
          {
            label: '物料规格',
            prop: 'productPartSpec',
            span: 8,
            labelWidth: '85',
            disabled: true
          }
        ]
      },
      importConfig: {
        show: false,
        importUrl: '/api/mes-product/key/material/config/import',
        exportName: '产品用料导入模版.xlsx',
        params: {},
        formData: {
          req: []
        },
        title: '产品用料导入'
      },
      warehouseList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.workorder_add, false),
        viewBtn: this.vaildData(this.permission.workorder_view, false),
        delBtn: this.vaildData(this.permission.workorder_delete, false),
        editBtn: this.vaildData(this.permission.workorder_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    basicInfoIndex() {
      let indexs = [];
      this.basicInfoSelectionList.forEach((ele) => {
        indexs.push(ele.$index);
      });
      return indexs;
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
      let urlQuery = this.$route.query;
      if (urlQuery && urlQuery.workOrderNo) {
        this.search.orderNo = decodeURIComponent(urlQuery.workOrderNo);
      }
    });
    getWarehouseList().then(
      (res) => {
        this.warehouseList = this._get(res, 'data.data', []);
      },
      (error) => {
        this.warehouseList = [];
      }
    );
  },
  activated() {
    // 1.设计工单工艺路线页面 点击前往修改 使用localStorage存储工单信息并打开工单用料配置弹框
    // 2.关闭工单用料配置弹窗将workOrderProcessInfo清除
    if (localStorage.getItem('workOrderProcessInfo') && localStorage.getItem('workOrderProcessInfo') != null) {
      let { id, orderNo, status, partMasterId } = JSON.parse(localStorage.getItem('workOrderProcessInfo'));
      this.workOrderMaterialsParams.workOrderId = id;
      this.workOrderMaterialsParams.workOrderNo = orderNo;
      this.workOrderMaterialsParams.partMasterId = partMasterId;
      if (id && orderNo && status === 0) {
        this.getBackProductMaterialByOrderId(id, partMasterId, Number(status));
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    handleJumpCache(this, next, from, '/product/workorder');
  },
  methods: {
    // 派工 撤回 完工 编辑工艺路线 查看工艺路线 绑定包装
    async handleMenu(params) {
      let { type } = params;
      if (this.selectionList.length === 0) {
        this.$message.warning('至少选择一条数据');
        return;
      }
      if (['processSync', 'gdesign', 'gread'].includes(type) && this.selectionList.length !== 1) {
        this.$message.warning('此功能不支持批量处理，只能选择一条数据');
        return;
      }
      // 工单完工，锁定，强制完工  无法编辑工艺路线
      // 1已撤回 2待生产 3生产中 4完工 5 锁定 7强制完工
      if (['gdesign'].includes(type)) {
        if ([5].includes(this.selectionList[0].status)) {
          this.$message.warning('当前勾选的工单为锁定状态，无法修改工艺路线！');
          return;
        }
        if ([4, 7].includes(this.selectionList[0].status)) {
          this.$message.warning('当前勾选的工单已完工，无法修改工艺路线！');
          return;
        }
      }
      if (['gdesign', 'gread'].includes(type)) {
        let { id, workOrderId, workOrderNo, productPartNo, productPartName, productPartId, packingConfigId, bomId, status } = this.selectionList[0];
        // 判断此物料是否有设计产品工艺路线
        if (type == 'gdesign') {
          let data = await checkProcessRoute(productPartId);
          if (data.data && data.data.code != 200) return;
        }
        this.$router.push({
          path: `/product/model-manage/orderroute-design/${type}`,
          query: {
            id,
            workOrderId: workOrderId,
            workOrderNo: encodeURI(workOrderNo),
            partMasterId: productPartId,
            partNo: productPartNo,
            partName: productPartName,
            bomId,
            packingConfigId,
            status,
            processId: id,
            routeConfigured: status
          }
        });
        return;
      }
      if (['processSync'].includes(type)) {
        this.handleProductProcessSync(this.selectionList[0].workOrderId);
        return;
      }
    },
    rowUpdate(form, index, done, loading) {
      update(form.id, form.remark).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this._forEach(this.data, (item) => {
            item.productionLineId = [];
            this._forEach(item.productionLineVoList, (listItem) => {
              item.productionLineId.push(listItem.id);
            });
          });
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    rowClick(row, column) {
      this.$util.table.rowClick(this.$refs.crud, row, this.selectionList);
    },
    handSelect() {
      this.$refs.crud.setCurrentRow();
    },
    selectionAll() {
      this.$refs.crud.setCurrentRow();
    },
    orderPartConfig() {
      if (this.selectionList.length === 0 || this.selectionList.length > 1) {
        this.$message.warning('请选择一条数据');
        return;
      }
      if (this.selectionList[0].status === 1) {
        this.$message.warning('工单未设计工艺路线，无法配置产品用料！');
        return;
      }
      this.getProductMaterialByOrderId();
    },
    productInfoRowSave(form, done) {
      done();
    },
    productInfoRowUpdate(form, index, done) {
      done();
    },
    productInfoRowDel(row, index) {
      this.productInfoList[this.selectTimeControlIndex].timeConditions = '';
      this.productInfoList.splice(index, 1);
      if (row.id) {
        this.materialControlsDeleteIds.push(row.id);
      }
    },
    basicInfoSelectionChange(list) {
      this.basicInfoSelectionList = list;
    },
    productInfoDelete() {
      this.basicInfoSelectionList = this.$refs.productInfoCrud.getCheckboxRecords();
      if (this.basicInfoSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let selectList = [];
        this.materialControlsDeleteIds = [];
        this._forEach(this.basicInfoIndex, (item) => {
          selectList.push(this.productInfoList[item]);
          if (this.productInfoList[item].id) {
            this.materialControlsDeleteIds.push(this.productInfoList[item].id);
          }
        });
        this._forEach(selectList, (item) => {
          let index = this.productInfoList.indexOf(item);
          this.productInfoList.splice(index, 1);
        });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.$refs.productInfoCrud.clearSelected();
      });
    },
    /**
     * 添加替代料
     */
    async handleAddMaterial(row, index) {
      this.alternativeMaterialsDialog = true;
      this.partForm.productPartNo = row.partNo;
      this.partForm.productPartSpec = row.partSpec;
      this.selectTimeControlIndex = index;
      this.alternativeMaterialsList = row.replacePartNo ? JSON.parse(row.replacePartNo) : [];
    },
    /**
     * 双击模态框行
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'partModal':
          for (let i = 0; i < row.length; i++) {
            this.productInfoList.push({
              $index: this.productInfoList.length,
              partMasterId: row[i].id,
              partNo: row[i].partNo,
              partName: row[i].name,
              partModel: row[i].partModel ? row[i].partModel : '',
              partSpec: row[i].partSpec,
              quantity: undefined,
              sectionId: '',
              isKeyMaterial: false,
              isBackflush: false
            });
          }
          break;
        case 'replacePartModal':
          let obj = this._find(this.alternativeMaterialsList, { partNo: row.partNo });
          if (obj) {
            this.$message({
              type: 'warning',
              message: '已存在相同物料，请重新选择！'
            });
            return;
          }
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partNo', row.partNo);
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partName', row.name);
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partModel', row.partModel ? row.partModel : '');
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partSpec', row.partSpec);
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'quantity', undefined);
          break;
        default:
          break;
      }
    },
    openSelectReplaceModal(index) {
      this.replaceRowIndex = index;
      this.addMaterial('replacePartModal');
    },
    /**
     * 添加物料
     */
    addMaterial(type) {
      this.modalName = type;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        rowSelectionType: type === 'replacePartModal' ? 'single' : 'multiple',
        isDefaultLoad: true,
        selectOption: {
          isMark: true
        },
        selectable: (row, index) => {
          return !this.productInfoList.map((item) => item.partMasterId).includes(row.id);
        },
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    addReplace() {
      this.alternativeMaterialsList.push({
        partNo: '',
        partName: '',
        partSpec: '',
        rate: '',
        quantity: undefined
      });
    },
    replacePartRowDel(index) {
      this.alternativeMaterialsList.splice(index, 1);
    },
    submitReplacePart() {
      for (let i = 0; i < this.alternativeMaterialsList.length; i++) {
        if (!this.alternativeMaterialsList[i].partNo) {
          this.$message({
            type: 'warning',
            message: '替代物料编码不能为空！'
          });
          return;
        }
        if (!this.alternativeMaterialsList[i].quantity && this.alternativeMaterialsList[i].quantity != 0) {
          this.$message({
            type: 'warning',
            message: `物料编码为${this.alternativeMaterialsList[i].partNo}的单位用量不能为空！`
          });
          return;
        }
        if (this.alternativeMaterialsList[i].quantity <= 0) {
          this.$message({
            type: 'warning',
            message: `物料编码为${this.alternativeMaterialsList[i].partNo}的单位用量不能小于等于0！`
          });
          return;
        }
      }
      const index = this.selectTimeControlIndex;
      this.$set(this.productInfoList[index], 'replacePartNo', JSON.stringify(this.alternativeMaterialsList));
      this.alternativeMaterialsDialog = false;
    },
    replaceClose() {
      this.partForm = {};
      this.alternativeMaterialsList = [];
    },
    /**
     * 修改工单用料配置
     */
    submit() {
      this.$refs.basicInfoForm.validate((valid, done) => {
        if (valid) {
          for (let i = 0; i < this.productInfoList.length; i++) {
            if (!this.productInfoList[i].quantity && this.productInfoList[i].quantity != 0 && this.productInfoList[i].partSubType !== 'INDIRECT') {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的单位用量不能为空！`
              });
              return;
            }
            if (this.productInfoList[i].quantity <= 0) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的单位用量不能小于等于0！`
              });
              return;
            }
            if (!this.productInfoList[i].sectionId) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的用料工段不能为空！`
              });
              return;
            }
            if (this.productInfoList[i].isBackflush && !this.productInfoList[i].backflushWarehouseId) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的物料已开启倒冲，倒冲仓库不能为空！`
              });
              return;
            }
            for (let j = i + 1; j < this.productInfoList.length; j++) {
              if (this.productInfoList[i].partNo === this.productInfoList[j].partNo && this.productInfoList[i].sectionId === this.productInfoList[j].sectionId) {
                this.$message({
                  type: 'warning',
                  message: `多个物料编码为${this.productInfoList[i].partNo}的用料工段不能被重复选择！`
                });
                return;
              }
            }
          }
          let params = {};
          let keyMaterialConfigDetailDtoList = this.productInfoList.map((item, index) => {
            let workSectionObj = this._find(this.sectionList, { sectionId: item.sectionId });
            let warehouseObj = this._find(this.warehouseList, { id: item.backflushWarehouseId });
            return {
              id: item.id,
              keyMaterialConfigId: item.keyMaterialConfigId,
              sequence: index + 1,
              partNo: item.partNo,
              partName: item.partName,
              partModel: item.partModel ? item.partModel : '',
              partSpec: item.partSpec,
              quantity: item.quantity,
              sectionId: item.sectionId,
              sectionName: workSectionObj ? workSectionObj.sectionName : '',
              materialProcessConfigurationId: item.materialProcessConfigurationId,
              materialProcessName: item.materialProcessName,
              isKeyMaterial: item.isKeyMaterial || false,
              isBackflush: item.isBackflush || false,
              backflushWarehouseId: item.backflushWarehouseId,
              backflushWarehouseCode: warehouseObj ? warehouseObj.code : '',
              replacePartNo: item.replacePartNo
            };
          });
          console.log(keyMaterialConfigDetailDtoList, 'keyMaterialConfigDetailDtoList');
          if (this.selectionList && this.selectionList[0]) {
            let { workOrderId, workOrderNo } = this.selectionList[0];
            params.workOrderId = workOrderId;
            params.workOrderNo = workOrderNo;
          } else {
            params.workOrderId = this.workOrderMaterialsParams.workOrderId;
            params.workOrderNo = this.workOrderMaterialsParams.workOrderNo;
          }

          params.id = this.basicInfoForm.id;
          params.productPartNo = this.basicInfoForm.productPartNo;
          params.productPartName = this.basicInfoForm.productPartName;
          params.productPartModel = this.basicInfoForm.productPartModel;
          params.type = 'WORKORDER';
          params.deletedIds = this.materialControlsDeleteIds;
          params.keyMaterialConfigDetailDtoList = keyMaterialConfigDetailDtoList;
          // 检验关键料追溯配置表是否有重复物料数据
          let partNoArray = this.productInfoList.map((item) => item.partNo);
          if (new Set(partNoArray).size !== partNoArray.length) {
            this.$message.warning('关键料追溯配置表中存在重复物料数据，请检查后重新提交！');
            return;
          }
          done();
          console.log(params, 'params');
          addOrUpdate(params).then(
            (res) => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.showDialog = false;
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    getProductMaterialByOrderId() {
      this.basicInfoForm.productPartNo = this.selectionList[0].productPartNo;
      this.basicInfoForm.productPartName = this.selectionList[0].productPartName;
      this.basicInfoForm.productPartId = this.selectionList[0].productPartId;
      this.showDialog = true;
      this.loading = true;
      getProductMaterialConfig(this.selectionList[0].workOrderId).then((res) => {
        this.showDialog = true;
        if (res.data.data) {
          this.basicInfoForm = res.data.data;
        }

        if ([0, 2, 3].includes(this.selectionList[0].status)) {
          this.productInfoOption.menu = true;
        } else {
          this.productInfoOption.menu = false;
        }
        // this.basicInfoForm.partMasterId = this._get(res, 'data.data.productPartId', '');
        this.processId = this.selectionList[0].processId;
        getSectionByPartId(this.selectionList[0].productPartId).then((res) => {
          let data = this._get(res, 'data.data.sections', []);
          if (data != null) {
            this.sectionList = data;
          } else {
            this.sectionList = [];
          }
          let result = this._get(this.basicInfoForm, 'details', []);
          this.productInfoList = result;
          this.loading = false;
          if (this.productInfoList === null) {
            this.productInfoList = [];
          }
          this._forEach(this.productInfoList, (item, index) => {
            try {
              item['$index'] = index;
            } catch (error) {
              console.log('error', error);
            }
          });
        });
      });
    },
    sectionChange(index) {
      this.$set(this.productInfoList[index], 'materialProcessConfigurationId', '');
      this.$set(this.productInfoList[index], 'materialProcessName', '');
      this.materialProcessChange(this.productInfoList[index].sectionId);
    },
    materialProcessChange(sectionId) {
      this.workProcessList = [];
      getConfiguration({ sectionId: sectionId }).then(
        (res) => {
          this.workProcessList = this._get(res, 'data.data', []);
        },
        (error) => {
          this.workProcessList = [];
        }
      );
    },
    handleChangeMaterialProcess(materialProcessName, rowIndex) {
      let materialProcessConfiguration = this.workProcessList.find((item) => item.materialProcessName === materialProcessName);
      let materialProcessConfigurationId = materialProcessConfiguration ? materialProcessConfiguration.id : '';
      console.log(materialProcessConfigurationId, 'materialProcessConfigurationId');
      this.$set(this.productInfoList[rowIndex], 'materialProcessConfigurationId', materialProcessConfigurationId);
    },
    getBackProductMaterialByOrderId(id, partMasterId, status) {
      getProductMaterialConfig(id).then((res) => {
        this.showDialog = true;
        this.basicInfoForm = res.data.data;
        if (status === 0) {
          this.productInfoOption.menu = true;
        } else {
          this.productInfoOption.menu = false;
        }
        this.basicInfoForm.partMasterId = this._get(res, 'data.data.partMasterId', '');
        getSectionByPartId(partMasterId).then((res) => {
          let data = this._get(res, 'data.data.sections', []);
          if (data != null) {
            this.sectionList = data;
          } else {
            this.sectionList = [];
          }
          this.productInfoList = this._get(this.basicInfoForm, 'materialControls', []);
          if (this.productInfoList === null) {
            this.productInfoList = [];
          }
          this._forEach(this.productInfoList, (item) => {
            item.partMasterId = item.partMasterId;
          });
        });
      });
    },
    closeDialog() {
      this.$refs.basicInfoForm.resetFields();
      this.basicInfoForm = {};
      this.productInfoList = [];
      this.materialControlsDeleteIds = [];
      localStorage.removeItem('workOrderProcessInfo');
    },
    handleView(row) {
      this.showDetailDialog = true;
      this.form = row;
      this.$nextTick(() => {
        this.$refs.form.allDisabled = true;
      });
      // getProcessLog(row.orderNo).then((res) => {
      //   this.logData = this._get(res, 'data.data', []);
      // });
    },
    handleProductProcessSync(workOrderId) {
      productProcessSync(workOrderId).then((res) => {
        if (res.data.code === 200) {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: `同步产品工艺成功!`
          });
          this.$refs.crud.toggleSelection();
        }
      });
    },
    beforeOpen(done, type) {
      done();
    },
    beforeClose(done, type) {
      done();
    },
    handleImport() {
      this.importConfig.show = true;
    },
    codeClose(value, data, fileParams) {
      this.onLoad();
    }
  }
};
</script>

<style lang="scss" scoped>
.subTitle {
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.85);
  .mr10 {
    margin-right: 10px;
  }
}

::v-deep .workorderRouteDialog .el-dialog__body {
  max-height: 75vh;
  overflow: auto;
  padding: 0 20px;
  .titleLeft {
    display: flex;
    border-bottom: 1px solid #eee;
    padding: 10px 0;
    margin-bottom: 10px;
    .titleName {
      font-size: 16px;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.85);
    }
  }
  .avue-form__menu {
    display: none;
  }
  .avue-crud__menu {
    display: none;
  }
}
.keyMaterialsDialog {
  ::v-deep .el-table__header {
    thead {
      th {
        background-color: #fafafa;
        padding: 8px 0;
        color: rgba(0, 0, 0, 0.85);
        font-size: 12px;
      }
    }
  }
}
.replaceDialog {
  ::v-deep .el-table__header {
    thead {
      th {
        background-color: #fafafa;
        padding: 8px 0;
        color: rgba(0, 0, 0, 0.85);
        font-size: 12px;
      }
    }
  }
  ::v-deep .el-input-group__append {
    padding: 0;
    .el-button {
      margin: 0;
      width: 50px;
    }
  }
}
</style>
